Running Bash commands in Python - Stack Overflow
Some summary:
- Use
subprocess.run()
- Be aware of the following argument possibilities with
subprocess.run()
:check=True
— Raises an error should the process failsstdout=subprocess.PIPE
andstderr=subprocess.PIPE
to capture outputs from processuniversal_newlines=True
(ortext=True
in Python 3.7) — Ensures thatstdout
andstderr
are encoded as unicode instead of byte stringsshell=True
- Pass a single string to your shell
- Able to take advantage of shell features like redirection, wildcard expansions, etc
shell=False
- (Default) Supply arguments as a list. Augment
shlex.split
to return appropriate list from a string. - More lightweight, reduces hidden complexities and minimizes chance of bugs and security problems
- Limitations of not using shell can be handled directly via Python
- (Default) Supply arguments as a list. Augment
env={‘foo’: ‘bar’}
— Exposes environmental variablefoo
with value”bar”
to subprocessexecutable:/bin/bash
— Specify which executable should execute this process